
package com.sskj.jkzx.service.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanComparator;
import org.apache.commons.collections.ComparatorUtils;
import org.apache.commons.collections.comparators.ComparableComparator;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sskj.jkzx.domain.entity.EngQueryParam;
import com.sskj.jkzx.domain.entity.basic.KeyValue;
import com.sskj.jkzx.domain.entity.eng.EngCamera;
import com.sskj.jkzx.domain.entity.eng.EngJdInfo;
import com.sskj.jkzx.domain.entity.eng.EngKqjlInfo;
import com.sskj.jkzx.vo.TimeLineBean;
import com.sskj.utils.HttpHelp;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import springfox.documentation.annotations.ApiIgnore;

@RestController
@RequestMapping(value = "**/sskj/xmmx")
@Api(value = "明细信息查询", description = "项目明细信息查询")
public class XmmxInfoServiceImpl {

	protected final Log logger = LogFactory.getLog(XmmxInfoServiceImpl.class);

	@Value("${sskj.jdServer}")
	private String jdServer;

	@Value("${sskj.tsServer}")
	private String tsServer;

	@Value("${sskj.cmisServer}")
	private String cmisServer;

	@Value("${sskj.hkCameraControlAPI}")
	private String hkCameraControlAPI;

	/***
	 * 项目工程监督基本信息
	 * 
	 * @return
	 */
	@CrossOrigin(origins = "*", maxAge = 3600)
	@RequestMapping(value = "/jdgc", method = RequestMethod.GET)
	@ApiOperation(value = "监督工程信息查询", httpMethod = "GET")
	@ApiImplicitParams({ @ApiImplicitParam(name = "jdgcId", value = "关键字", paramType = "form", dataType = "string") })
	public EngJdInfo queryEngJdInfo(@ApiIgnore EngQueryParam engQueryParam) {

		EngJdInfo result = new EngJdInfo();

		try {
			JSONObject param = new JSONObject();
			param.put("jdgcId", engQueryParam.getJdgcId());
			// param.put("srvName", "ythpt");
			// param.put("srvPwd", "ythpt");
			String str = HttpHelp.sendPut(jdServer + "/seam/resource/v1/jkzx/eng/jdinfo",
					param.toJSONString());

			result = JSON.parseObject(str, EngJdInfo.class);
		} catch (Exception e) {
			logger.info(e.getMessage());
		}

		logger.info(JSONObject.toJSONString(result));
		return result;
	}

	@CrossOrigin(origins = "*", maxAge = 3600)
	@RequestMapping(value = "/error", method = RequestMethod.GET)
	@ApiOperation(value = "监督工程违规查询", httpMethod = "GET")
	public List<KeyValue> queryEngErrorInfo(EngQueryParam engQueryParam) {

		List<KeyValue> results = new ArrayList<KeyValue>();

		try {
			String str = HttpHelp.sendGet(jdServer + "/seam/resource/v1/jkzx/eng/error/" + engQueryParam.getJdgcId(),
					null);

			if (str != null) {
				results.addAll(JSON.parseArray(str, KeyValue.class));
			}
		} catch (Exception e) {
			logger.info(e.getMessage());
		}

		logger.info(JSONArray.toJSONString(results));

		return results;
	}

	@CrossOrigin(origins = "*", maxAge = 3600)
	@RequestMapping(value = "/timeline", method = RequestMethod.GET)
	@ApiOperation(value = "监督工程时间轴", httpMethod = "GET")
	public List<TimeLineBean> queryEngTimeInfo(EngQueryParam engQueryParam) {

		List<TimeLineBean> results = new ArrayList<TimeLineBean>();

		try {
			String str = HttpHelp.sendPost(cmisServer + "/seam/resource/v1/jkzx/eng/timeline/",
					JSON.toJSONString(engQueryParam));

			if (str != null) {
				results.addAll(JSON.parseArray(str, TimeLineBean.class));
			}
		} catch (Exception e) {
			logger.info(e.getMessage());
		}

		try {
			String strs = HttpHelp.sendPost(jdServer + "/seam/resource/v1/jkzx/eng/timeline/",
					JSON.toJSONString(engQueryParam));

			if (strs != null) {
				results.addAll(JSON.parseArray(strs, TimeLineBean.class));
			}
		} catch (Exception e) {
			logger.info(e.getMessage());
		}

		sort(results, "time", true);

		logger.info(JSONArray.toJSONString(results));

		return results;
	}

	/**
	 * 项目人员考勤记录查询
	 * 
	 * @param engQueryParam
	 */
	@CrossOrigin(origins = "*", maxAge = 3600)
	@RequestMapping(value = "/engkq", method = RequestMethod.GET)
	@ApiOperation(value = "监督工程人员考勤记录", httpMethod = "GET")
	public List<EngKqjlInfo> queryRykq(EngQueryParam engQueryParam) {
		List<EngKqjlInfo> results = new ArrayList<EngKqjlInfo>();

		try {
			String str = HttpHelp.sendGet(jdServer + "/seam/resource/v1/jkzx/kq/search/" + engQueryParam.getJdgcId(),
					null);
			if (str != null) {
				results.addAll(JSON.parseArray(str, EngKqjlInfo.class));
			}
		} catch (Exception e) {
			logger.info(e.getMessage());
		}

		return results;
	}

	@CrossOrigin(origins = "*", maxAge = 3600)
	@RequestMapping(value = "/camera", method = RequestMethod.GET)
	@ApiOperation(value = "监督工程监控摄像头信息获取", httpMethod = "GET")
	public List<EngCamera> queryCamera(EngQueryParam engQueryParam) {
		List<EngCamera> cameras = new ArrayList<EngCamera>();
		String monitorData = getMonitorData(engQueryParam.getJdgcId());
		if (monitorData != null) {
			cameras = JSON.parseArray(monitorData, EngCamera.class);
		}
		return cameras;
	}

	public String getMonitorData(String projectId) {
		String lines = "";
		String url = jdServer + hkCameraControlAPI + "/querybycode";
		url += "/" + projectId;
		HttpPut httpput = new HttpPut(url);
		CloseableHttpResponse response = null;
		CloseableHttpClient httpClient = HttpClients.createDefault();
		RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000).build();
		httpput.setConfig(requestConfig);
		httpput.addHeader("Content-Type", "application/json");
		try {
			StringEntity requestEntity = new StringEntity("", "utf-8");
			httpput.setEntity(requestEntity);
			response = httpClient.execute(httpput, new BasicHttpContext());
			if (response.getStatusLine().getStatusCode() != 200) {
				System.out.println(
						"request url failed, http code=" + response.getStatusLine().getStatusCode() + ", url=" + url);
				return null;
			}
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				lines = EntityUtils.toString(entity, "utf-8");
			}
		} catch (IOException e) {
			System.out.println("request url=" + url + ", exception, msg=" + e.getMessage());
			e.printStackTrace();
		} finally {
			if (response != null)
				try {
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}
		return lines;
	}

	/**
	 * `
	 * 
	 * @describe 依据某个字段对集合进行排序
	 * @author ...
	 * @date 2013-1-22 下午3:44:47
	 * @param list
	 *            待排序的集合
	 * @param fieldName
	 *            依据这个字段进行排序
	 * @param asc
	 *            如果为true，是正序；为false，为倒序
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public <T> void sort(List<T> list, String fieldName, boolean asc) {

		Comparator<?> mycmp = ComparableComparator.getInstance();
		mycmp = ComparatorUtils.nullLowComparator(mycmp); // 允许null
		if (!asc) {
			mycmp = ComparatorUtils.reversedComparator(mycmp); // 逆序
		}
		Collections.sort(list, new BeanComparator(fieldName, mycmp));
	}

}
